import { LintGuardOptions } from './config'
import lintStaged from 'lint-staged'
import { printError, printSuccess } from './formatter'
export class LintGuard {
    private options: LintGuardOptions

    constructor(options: LintGuardOptions = {}) {
        this.options = {
            concurrent: true,
            shell: false,
            quiet: false,
            relative: false,
            debug: false,
            stash: true,
            allowEmpty: true,
            ...options
        }
    }
    private async runHooks(
        hooks?: Array<(...args: any[]) => Promise<void>>,
        ...args: any[]
    ): Promise<void> {
        if (!hooks) return

        for (const hook of hooks) {
            try {
                await hook(...args)
            } catch (error) {
                printError('Hook execution failed:', error)
            }
        }
    }

    public async execute(): Promise<boolean> {
        try {
            // 执行前置钩子
            await this.runHooks(this.options.beforeHooks)

            // 准备 lint-staged 配置
            const results = await lintStaged({
                config: this.options.config,
                cwd: this.options.cwd,
                concurrent: this.options.concurrent,
                maxArgLength: this.options.maxArgLength,
                shell: this.options.shell,
                quiet: this.options.quiet,
                relative: this.options.relative,
                debug: this.options.debug,
                stash: this.options.stash,
                allowEmpty: this.options.allowEmpty
            })
            console.log(results)

            this.formatResults(results)
            await this.runHooks(this.options.afterHooks, results, results)

            return results // 关键修复点
        } catch (error: any) {
            if (this.options.onError) {
                this.options.onError(error)
            } else {
                this.formatError(error)
            }

            await this.runHooks(this.options.afterHooks, false, error)
            return false
        }
    }

    public addCustomValidator(validator: () => Promise<boolean>): this {
        this.options.beforeHooks = this.options.beforeHooks || []
        this.options.beforeHooks.push(async () => {
            const isValid = await validator()
            if (!isValid) throw new Error('Custom validation failed')
        })
        return this
    }

    public addCustomFormatter(formatter: (results: any | Error) => void): this {
        this.options.customFormatters = this.options.customFormatters || []
        this.options.customFormatters.push(formatter)
        return this
    }
    // 添加自定义输出格式化器
    private formatResults(results: any): void {
        if (this.options.customFormatters) {
            this.options.customFormatters.forEach((formatter) => formatter(results))
        } else {
            results
                ? printSuccess('✅ All lint checks passed!')
                : printError('❌ Some lint checks failed!')
        }
    }
    private formatError(error: any): void {
        printError('❌ Lint execution failed')

        if (error instanceof Error) {
            printError(error.message)
        } else if (typeof error === 'object' && error.errors) {
            error.errors.forEach((err: any) => {
                if (err.filePath && err.stdout) {
                    printError(`File: ${err.filePath}`)
                    printError(err.stdout)
                } else {
                    printError(err.message || err.toString())
                }
            })
        } else {
            printError(String(error))
        }
        if (this.options.customFormatters) {
            this.options.customFormatters.forEach((formatter) => formatter(error))
        }
    }
}
